package com.source.lightfowl.basedata.service.impl;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.source.lightfowl.basedata.dao.BarcodeMachineDao;
import com.source.lightfowl.basedata.dao.MachineAlertDao;
import com.source.lightfowl.basedata.dao.StallsDao;
import com.source.lightfowl.basedata.entity.BarcodeMachine;
import com.source.lightfowl.basedata.entity.Stalls;
import com.source.lightfowl.basedata.service.MachineAlertService;
import com.source.lightfowl.utils.StringTOArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.source.lightfowl.basedata.entity.MachineAlert;
import java.util.ArrayList;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author: Faink
 * @CreateTime: 2020/8/4 20:44
 */
@Service
public class MachineAlertServiceimpl implements MachineAlertService {

    @Autowired
    private MachineAlertDao machineAlertDao;

    @Autowired
    private StallsDao stallsDao;
    @Autowired
    private BarcodeMachineDao machineDao;

    @Override
    public Page<MachineAlert> findAll(int page, int size) {
        return machineAlertDao.findAll(PageRequest.of(page-1, size));
    }

    @Override
    public List<MachineAlert> findAll() {
        List<MachineAlert> all = machineAlertDao.findAll();
        List<MachineAlert> collect = all.stream().map(s -> {
            String barcodeMachineId = s.getBarcodeMachineId(); //获取脚标机id
            Optional<BarcodeMachine> optional = machineDao.findById(barcodeMachineId); //获取脚标机
            if (optional.isPresent()) {
                BarcodeMachine machine = optional.get();
                String stallsId = machine.getStallsId(); //获取脚标机对应的档口id
                Integer value = Integer.valueOf(stallsId);
                Optional<Stalls> stalls = stallsDao.findById(value);  //获取档口
                if (stalls.isPresent()) {
                    Stalls stalls1 = stalls.get();
                    s.setStallsName(stalls1.getStallsName());  //设置档口名
                    s.setLinkName(stalls1.getContacts()); //设置联系人
                }
            }
            return s;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public Page<MachineAlert> findAllBySearch(Map whereMap, int page, int size) {
        Specification<MachineAlert> specification = createSpecification(whereMap);
        PageRequest pageRequest =  PageRequest.of(page-1, size);
        return machineAlertDao.findAll(specification, pageRequest);
    }

    @Override
    public MachineAlert findById(String id) {
        Optional<MachineAlert> optional = machineAlertDao.findById(id);
        if (optional.isPresent()){
            MachineAlert s = optional.get();
            String barcodeMachineId = s.getBarcodeMachineId(); //获取脚标机id
            Optional<BarcodeMachine> optional2 = machineDao.findById(barcodeMachineId); //获取脚标机
            if (optional2.isPresent()) {
                BarcodeMachine machine = optional2.get();
                String stallsId = machine.getStallsId(); //获取脚标机对应的档口id
                Integer value = Integer.valueOf(stallsId);
                Optional<Stalls> stalls = stallsDao.findById(value);  //获取档口
                if (stalls.isPresent()) {
                    Stalls stalls1 = stalls.get();
                    s.setStallsName(stalls1.getStallsName());  //设置档口名
                    s.setLinkName(stalls1.getContacts()); //设置联系人
                }
            }
            return s;
        }
        return new MachineAlert();
    }

    @Override
    public void update(MachineAlert machineAlert) {
        machineAlertDao.save(machineAlert);
    }

    @Override
    public void update(String id) {
        machineAlertDao.updateRead(id);
    }

    @Override
    public void updateBatchRead(String ids) {
        ArrayList<Integer> list = StringTOArrayList.toArrayList(ids);
        if(list != null) {
            machineAlertDao.updateBatchRead(list);
        }else {
            System.out.println("批量删除传递参数出错");
            throw new RuntimeException("传递的id参数格式出错，id之间需要用英文逗号分隔开，以字符串格式传递");
        }

    }

    @Override
    public void deleteById(String id) {
        machineAlertDao.deleteById(id);
    }

    @Override
    public void deleteBatch(String ids) {
        ArrayList<Integer> list = StringTOArrayList.toArrayList(ids);
        if(list != null) {
            machineAlertDao.deleteBatch(list);
        }else {
            System.out.println("批量删除传递参数出错");
            throw new RuntimeException("传递的id参数格式出错，id之间需要用英文逗号分隔开，以字符串格式传递");
        }
    }

    private Specification<MachineAlert> createSpecification(Map searchMap) {

        return new Specification<MachineAlert>() {

            @Override
            public Predicate toPredicate(Root<MachineAlert> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                //
                if (searchMap.get("id")!=null && !"".equals(searchMap.get("id"))) {
                    predicateList.add(cb.like(root.get("id").as(String.class), "%"+(String)searchMap.get("id")+"%"));
                }
                // 脚标机编号
                if (searchMap.get("barcodeMachineId")!=null && !"".equals(searchMap.get("barcodeMachineId"))) {
                    predicateList.add(cb.like(root.get("barcodeMachineId").as(String.class), "%"+(String)searchMap.get("barcodeMachineId")+"%"));
                }
                // 故障信息
                if (searchMap.get("faultInfo")!=null && !"".equals(searchMap.get("faultInfo"))) {
                    predicateList.add(cb.like(root.get("faultInfo").as(String.class), "%"+(String)searchMap.get("faultInfo")+"%"));
                }
                // 故障状态（0：未处理、1：已处理）
                if (searchMap.get("state")!=null && !"".equals(searchMap.get("state"))) {
                    predicateList.add(cb.like(root.get("state").as(String.class), "%"+(String)searchMap.get("state")+"%"));
                }
                // 备注
                if (searchMap.get("remarks")!=null && !"".equals(searchMap.get("remarks"))) {
                    predicateList.add(cb.like(root.get("remarks").as(String.class), "%"+(String)searchMap.get("remarks")+"%"));
                }

                return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));

            }
        };

    }



}
